/**
 * Created by YMP on 2020/3/2.
 */

/**
 * 发表时间 几秒前 几分前 几小时前
 * @param ms
 * @returns {string}
 */
export function formatTimeBefore(ms) {
  var days = Math.floor(ms / (1000 * 60 * 60 * 24))
  var hours = Math.floor((ms % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  var minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60))
  var seconds = Math.floor((ms % (1000 * 60)) / 1000)
  if (days) {
    return days + '天前'
  }
  if (hours) {
    return hours + '小时前'
  }
  if (minutes) {
    return minutes + '分钟前'
  }
  if (seconds) {
    return seconds + '秒前'
  } else {
    return '刚刚'
  }
}
/**
 * 时间戳转化为日期
 * @param timestamp
 * @param type
 * @returns {string}
 */
export function dateFormat(time, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!time) return ''
  var t = new Date(time)
  var tf = function(i) {
    return (i < 10 ? '0' : '') + i
  }
  return format.replace(/YYYY|MM|M|DD|D|HH|H|mm|m|ss|s/g, function(a) {
    switch (a) {
      case 'YYYY':
        return tf(t.getFullYear())
      case 'MM':
        return tf(t.getMonth() + 1)
      case 'M':
        return t.getMonth() + 1
      case 'DD':
        return tf(t.getDate())
      case 'D':
        return t.getDate()
      case 'HH':
        return tf(t.getHours())
      case 'H':
        return t.getHours()
      case 'mm':
        return tf(t.getMinutes())
      case 'm':
        return t.getMinutes()
      case 'ss':
        return tf(t.getSeconds())
      case 's':
        return t.getSeconds()
    }
  })
}

/**
 * 解析url
 * @param url
 */

export function parseQuery(url) {
  var queryObj = {}
  var reg = /[?&]([^=&#]+)=([^&#]*)/g
  var querys = decodeURIComponent(url).match(reg)
  if (querys) {
    for (var i in querys) {
      var query = querys[i].split('=')
      var key = query[0].substr(1),
        value = query[1]
      queryObj[key] ? (queryObj[key] = [].concat(queryObj[key], value)) : (queryObj[key] = value)
    }
  }
  return queryObj
}
/**
 * 获取对象的长度
 * @param input
 * @returns {number}
 */
export function objLength(input) {
  let length = 0
  if (Object.prototype.toString.call(input) == '[object Object]') {
    console.error('输入必须为对象{}！')
  } else {
    /* eslint-disable-next-line  no-unused-vars */
    for (let key in input) {
      if (typeof key !== 'number') {
        length++
      }
    }
  }
  return length
}

/**
 * 验证是否是手机号码
 * @param number
 * @returns {boolean}
 */
export function vailPhone(number) {
  let flag = false
  let myreg = /^1[3-9][0-9]{9}$/
  if (!myreg.test(number)) {
    flag = false
  } else {
    flag = true
  }
  return flag
}

/**
 * 手机号掩码
 * @param input
 * @returns {*}
 */
export function maskPhone(input) {
  return input.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/**
 * 去除字符串所有空格
 * @param text
 * @returns {*}
 */
export function sTrim(text) {
  return text.replace(/\s/gi, '')
}

/**
 * 去除所有:
 * @param txt
 * @returns {*}
 */
export function replaceMaohao(txt) {
  return txt.replace(/\:/gi, '')
}
/**
 * 过滤金钱currency(100, '￥', 3)==>￥100.000
 * @param value
 * @param _currency
 * @param decimals
 * @returns {string}
 */
export function currency(value, _currency, decimals) {
  value = parseFloat(value)
  // eslint-disable-next-line no-restricted-globals
  if (!isFinite(value) || (!value && value !== 0)) return ''
  _currency = _currency != null ? _currency : '$' // 默认金钱符号
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified
  var i = _int.length % 3
  var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''
  var _float = decimals ? stringified.slice(-1 - decimals) : ''
  var sign = value < 0 ? '-' : ''
  var digitsRE = /(\d{3})(?=\d)/g
  return sign + _currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float
}

/**
 * 保留小数
 * @param num
 * @param s
 * @returns {string}
 */

export function tofixed(num, s) {
  let times = Math.pow(10, s + 1),
    des = parseInt(num * times),
    rest = des % 10
  if (rest == 5) {
    return ((parseFloat(des) + 1) / times).toFixed(s)
  }
  return num.toFixed(s)
}

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
export function debounce(func, wait, immediate) {
  let timeout
  return function() {
    let context = this
    let args = arguments
    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
  }
}
/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 */
export function throttle(func, wait, type) {
  if (type === 1) {
    var previous = 0
  } else if (type === 2) {
    var timeout
  }
  return function() {
    let context = this
    let args = arguments
    if (type === 1) {
      let now = Date.now()
      if (now - previous > wait) {
        func.apply(context, args)
        previous = now
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(() => {
          timeout = null
          func.apply(context, args)
        }, wait)
      }
    }
  }
}
export function getRequest(url) {
  let theRequest = new Object()
  url = decodeURIComponent(url)
  console.log(url)
  let str = url.substr(0)
  let strs = str.split('&')
  for (let i = 0; i < strs.length; i++) {
    theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
  }
  return theRequest
}
/**
 * 判断数组
 * @param {*} array
 */
export function isArray(array) {
  return array && Array.isArray(array)
}
/**
 * 获取对象keys
 * @param {*} obj
 */
export function keys(obj) {
  const REGEXP = new RegExp('{|}|"', 'g')
  return JSON.stringify(obj)
    .replace(REGEXP, '')
    .split(',')
    .map(function(item) {
      return item.split(':')[0]
    })
}
